package cn.yangmin.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/**
 * @author diandian
 * @date 2021-12-10 11:11
 */
@Component
@Slf4j
public class IPBlackListFilter implements GlobalFilter {
    private String[] blist=new String[]{"127.168.27.90"};

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求人的ip地址
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String ip = remoteAddress.getAddress().toString().substring(1);

        // 判断一下  如果不在黑名单  就放行
        if (isForbidden(ip)) {
            //  否则  拒绝访问  403
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }else {
            return chain.filter(exchange);
        }
    }

    private boolean isForbidden(String ip) {
        for (String s : blist) {
            if (ip.equals(s)) {
                return true;
            }
        }
        return false;
    }
}
